



class PropertiesUtil(object):
    """ Properties 文件解析类
    """

    def __init__(self, filename):
        self.filename = filename
        self.properties = {}

    def set_dict(self, field, dict_data, value):
        if (field.find('.') > 0):
            k = field.split('.')[0]
            dict_data.setdefault(k, {})
            return self.set_dict(field[len(k) + 1:], dict_data[k], value)
        else:
            if value.lower() in ["true","1"]:
                dict_data[field] = True
            elif value.lower() in ["false","0"]:
                dict_data[field] = False
            elif value.isdigit():
                dict_data[field] = int(value)
            else:
                dict_data[field] = value

    def get_properties(self):
        """
        :return:
        """
        try:
            with open(self.filename, "r") as fp:
                content = fp.readlines()
            for line in content:
                line = line.strip().replace('\n', '')
                if line.find("#") != -1:
                    line = line[0:line.find('#')]
                if line.find('=') > 0:
                    fields = line.split('=')
                    fields[1] = line[len(fields[0]) + 1:]
                    self.set_dict(fields[0].strip(), self.properties, fields[1].strip())
        except Exception as ex:
            raise ValueError(ex)
        return self.properties